<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card style="margin-top: 30px">
      <el-row>
        <el-col :span="24" style="margin-bottom: 20px">
          <el-button type="primary" @click="addroles">添加角色</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-table border  :data="roleslist">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <div class="expand_box">
                  <div v-if="scope.row.children.length > 0">
                    <el-row
                      
                      v-for="item1 in scope.row.children"
                      :key="item1.id"
                    >
                      <el-col :span="6">
                        <el-tag
                          @close="
                            deleteRoleRights(scope.row, scope.row.id, item1.id)
                          "
                          closable
                          >{{ item1.authName }}</el-tag
                        >
                      </el-col>
                      <el-col :span="18" class="btn-top"> 
                        <el-row
                          class="borderBtm_1px"
                          v-for="item2 in item1.children"
                          :key="item2.id"
                        >
                          <el-col :span="6">
                            <el-tag
                              @close="
                                deleteRoleRights(
                                  scope.row,
                                  scope.row.id,
                                  item2.id
                                )
                              "
                              type="success"
                              closable
                              >{{ item2.authName }}</el-tag
                            >
                          </el-col>
                          <el-col :span="18">
                            <el-tag
                              @close="
                                deleteRoleRights(
                                  scope.row,
                                  scope.row.id,
                                  item3.id
                                )
                              "
                              closable
                              type="warning"
                              v-for="item3 in item2.children"
                              :key="item3.id"
                            >
                              {{ item3.authName }}
                            </el-tag>
                          </el-col>
                        </el-row>
                      </el-col>
                    </el-row>
                  </div>
                  <div v-else>该角色暂无权限</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="roleName" label="角色名称"></el-table-column>
            <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  icon="el-icon-edit"
                  type="primary"
                  @click="editrole(scope.row)"
                  >编辑</el-button>
                <el-button
                  size="mini"
                  icon="el-icon-delete"
                  type="danger"
                  @click="del(scope.row.id)"
                  >删除</el-button>
                <el-button
                  size="mini"
                  icon="el-icon-s-tools"
                  type="warning"
                  @click="setRightsDia(scope.row)"
                  >分配权限</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加弹框-->
    <el-dialog title="添加" :visible.sync="dialogVisible">
      <span slot="footer" class="dialog-footer">
        <el-form ref="roleref" :rules="rules" :model="roledata">
          <el-form-item label-width="80px" label="角色名称" prop="roleName">
            <el-input v-model="roledata.roleName"></el-input>
          </el-form-item>
          <el-form-item label-width="80px" label="角色描述" prop="roleDesc">
            <el-input v-model="roledata.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="okok">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑弹框 -->
    <el-dialog title="编辑" :visible.sync="bianji">
      <span slot="footer" class="dialog-footer">
        <el-form ref="editroleref" :rules="rules" :model="roledata">
          <el-form-item label-width="80px" label="角色名称" prop="roleName">
            <el-input v-model="roledata.roleName"></el-input>
          </el-form-item>
          <el-form-item label-width="80px" label="角色描述" prop="roleDesc">
            <el-input v-model="roledata.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="bianji = false">取 消</el-button>
        <el-button type="primary" @click="qqqq">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 权限弹框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="isSetRights"
       width="30%"
      :before-close="handleClose"
    >
      <!-- 
      tree组件参数含义：
      data:数据源
      show-checkbox：是否有复选框
      node-key:tree组件的唯一标识
      default-expand-all:是否全部展开
      default-expanded-keys：[2,4,5 ]只展开给出的id节点的数组
      default-checked-keys:[3232,23,23,23,23,23,23],设置选中的id组成的数组
      props:配置数据源的选项  label:设置显示的名称,children:设置子级属性名称
     -->
      <el-tree
        :data="treeList"
        ref="treeRef"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="checkArr"
        :props="defaultProps"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isSetRights = false">取 消</el-button>
        <el-button type="primary" @click="SetRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //已选中的权限id组成的数组
      checkArr: [],
      list: [],
      treeList: [],
      defaultProps: {
        children: "children",
        label: "authName",
      },
      currentRoleID:"",
      roleslist: [],
      dialogVisible: false,
      bianji: false,
      isSetRights: false,
      //   添加角色
      roledata: {
        roleName: "",
        roleDesc: "",
      },
      //   修改角色
      editid:'',
      roleid: 0,
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getroles();
  },
  methods: {
    // 确认分配权限
   async  SetRights(){
     const Allcheckid = this.$refs.treeRef.getCheckedKeys()
     const halfcheckid = this.$refs.treeRef.getHalfCheckedKeys()
    const mergeCheckArr = [...Allcheckid,halfcheckid]
    const AllcheckidStr = mergeCheckArr.join(",")
    console.log(this.AllcheckidStr);
    const res = await this.$API.RoleRightAPI(this.currentRoleID,AllcheckidStr)
    console.log("确认分配权限",res);
    this.getroles()
    this.isSetRights = false
  },
    //监听关闭分配权限对话框
    handleClose() {
      console.log("监听关闭分配权限对话框");
      this.checkArr = [];
      this.isSetRights = false;
    },
    //打开分配权限对话框
    async setRightsDia(row) {
      //清空上次选择的结果
      this.checkArr = [];
      this.isSetRights = true;
      const res = await this.$API.RoletreeAPI("tree");
      this.treeList = res;
      this.currentRoleID=row.id
      this.getCheckedIds(row, this.checkArr);

      console.log("id数组：", this.checkArr);
    },
    //递归获取权限id方法
    getCheckedIds(row, checkArr) {
      console.log("11111:", row);
      console.log("22222:", checkArr);

      //没有children,就代表已经是最后一项，如果是最后一项，则把它的id，push给一个数组
      if (!row.children) {
        return checkArr.push(row.id);
      }

      row.children.forEach((item) => {
        this.getCheckedIds(item, checkArr);
      });
    },
    //删除角色指定的权限
    async deleteRoleRights(row, roleId, rightId) {
      //调删除删除角色指定的权限接口，返回最新权限列表
      const res = await this.$API.RoletreedelAPI(roleId, rightId);

      //更新当前角色权限
      row.children = res;
      //更新角色列表
    },

    //   编辑按钮弹出框
    editrole(row) {
      this.roledata.roleName = row.roleName;
      this.roledata.roleDesc = row.roleDesc;
      this.editid = row.id;
      this.bianji = true;
    },
    // 编辑确定按钮
    qqqq() {
      this.$refs.editroleref.validate(async (vaild) => {
        if (!vaild) return;
        const res = await this.$API.editRolesApi(this.editid,this.roledata);
        console.log(res);
        this.bianji = false;
        this.getroles();
        this.roledata = {};
      });
    },
    //   添加确定
    okok() {
      //检验表单是否符合规则
      this.$refs.roleref.validate(async (vaild) => {
        if (!vaild) return;
        const res = await this.$API.addRolesApi(this.roledata);
        console.log("添加角色：", res);
        this.dialogVisible = false;
        this.roledata = {
          roleName: "",
          roleDesc: "",
        };
        this.getroles();
      });
    },
    //   添加按钮
    addroles() {
      this.roledata = {};
      this.dialogVisible = true;
    },
    //  角色列表
    async getroles() {
      const res = await this.$API.rolesAPI();
      console.log("角色列表", res);
      this.roleslist = res;
      // this.getroles()
    },
    // 删除
    async del(id) {
      const res = await this.$confirm(
        "此操作将永久删除该文件，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => {
        this.$message({
          type: error,
          message: "已取消删除",
        });
      });
      if (res === "confirm") {
        await this.$API.DelRolesApi(id);
        this.getroles();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.btn-top{
    border-bottom: 2px solid #ccc;
}
.el-tag {
    margin: 15px;
}
</style>